import React, { useEffect } from "react";
import { Modal, Form, Select, Button } from "antd";
import { Role } from "../../../../api/type/ckgl";
const { Option } = Select;

interface AddRolesToUserModalProps {
  visible: boolean;
  onCancel: () => void;
  onOk: (selectedRoles: number[]) => void;
  roles: Role[];
  defaultValue?: { role_id: number };
}

const AddRolesToUserModal: React.FC<AddRolesToUserModalProps> = ({
  visible,
  onCancel,
  onOk,
  roles,
  defaultValue = { roles: [] },
}) => {
  const [form] = Form.useForm();

  useEffect(() => {
    if (Object.keys(defaultValue).length === 0) {
      form.resetFields();
    } else {
      form.setFieldsValue({
        ...defaultValue,
      });
    }
  }, [defaultValue, visible]);

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      onOk(values);
    } catch (errorInfo) {
      console.log("Failed:", errorInfo);
    }
  };

  return (
    <Modal
      title="修改用户角色"
      visible={visible}
      onOk={handleOk}
      onCancel={onCancel}
      footer={[
        <Button key="cancel" onClick={onCancel}>
          取消
        </Button>,
        <Button key="ok" type="primary" onClick={handleOk}>
          确定
        </Button>,
      ]}
    >
      <Form form={form}>
        <Form.Item
          label="用户角色"
          name="role_id"
          rules={[
            {
              required: true,
              message: "请选择用户角色",
            },
          ]}
        >
          <Select placeholder="请选择用户角色" allowClear>
            {roles.map((role) => (
              <Option key={role.id} value={role.id}>
                {role.name}
              </Option>
            ))}
          </Select>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default AddRolesToUserModal;
